package com.shiguiwu.springmybatis.netty.chat.group.handler;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;
import lombok.extern.slf4j.Slf4j;

import java.util.Date;

/**
 * @description:
 * @author: stone
 * @date: Created by 2022/11/14 20:22
 * @version: 1.0.0
 * @pakeage: com.shiguiwu.springmybatis.netty.chat.group.chat.group.handle
 */
@Slf4j
public class GroupChatServerHandler  extends SimpleChannelInboundHandler<String> {

    //定义一个channle 组，管理所有的channel
    //GlobalEventExecutor.INSTANCE) 是全局的事件执行器，是一个单例
    private static ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);


    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        channelGroup.writeAndFlush("[客户端]" + channel.remoteAddress() + " 加入聊天" + DateUtil.format(new Date(),
                DatePattern.NORM_DATETIME_FORMAT) + " \n");
        channelGroup.add(channel);

    }


    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        channelGroup.writeAndFlush("[客户端]" + channel.remoteAddress() + "离开了");
        log.info("当前在线人数 ====> {}", channelGroup.size());
    }


    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        //这个是给服务端看的，客户端上面已经提示xxx加入群聊了
        log.info("客户端 {} 上线了", ctx.channel().remoteAddress());
    }


    //表示channel 处于不活动状态, 提示 xx离线了
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        log.info("客户端 {} 离线了", ctx.channel().remoteAddress());
    }


    //读取数据，转发给在线的每一个客户端
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
        //获取通道
        Channel channel = ctx.channel();
        //回显信息，转发所有信息
        channelGroup.forEach(e -> {
            if (e != channel) {
                e.writeAndFlush("[客户] " + e.remoteAddress() + "发送了 ==> " + msg);
            }
            else {
                e.writeAndFlush("[自己] " + e.remoteAddress() + "发送了 ==> " + msg);
            }

        });
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        log.error("服务器异常 ====> {}", cause.getMessage());
        ctx.close();
    }
}
